package com.thekernel.youdaoyun.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.thekernel.youdaoyun.bean.User;
import com.thekernel.youdaoyun.exception.MyException;
import com.thekernel.youdaoyun.exception.impl.SystemErrorException;
import com.thekernel.youdaoyun.mapper.UserMapper;
import com.thekernel.youdaoyun.util.PasswordUtils;
import com.thekernel.youdaoyun.util.ResponseUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * @Author: thekernel
 * @Date: 2020/3/27 21:04
 * @Version: 1.0
 * @Description:
 */
@RestController
@RequestMapping("/sms")
public class SMSController {

    @Autowired
    private UserMapper userMapper;

    private final String ACCESS_KEY_ID = "LTAI4Fn1AnpeKLucEfh247jA";
    private final String ACCESS_SECRET = "T0kYwcHBCvxTy6ADzRYa6D5sO8viuu";
    private final String SIGN_NAME = "云上校招";

    private static char[] codeSequence = {
            '1', '2', '3', '4', '5', '6', '7', '8', '9'
    };

    @ApiOperation(value = "发送短信验证码", notes = "短信验证码接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phoneNumber", value = "手机号", required = true, dataType = "string")
    })
    @PostMapping("send")
    public @ResponseBody
    String sendRegisterSMS(@RequestBody JSONObject data) throws MyException {
        String phoneNumber = (String) data.get("phoneNumber");
        String verifyCode = PasswordUtils.generateVerificationCode(codeSequence, 4);
        HttpSession session = ((ServletRequestAttributes)
                Objects.requireNonNull(RequestContextHolder.getRequestAttributes()))
                .getRequest()
                .getSession();

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", ACCESS_KEY_ID, ACCESS_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        // 需要修改为已注册的签名
        request.putQueryParameter("SignName", SIGN_NAME);
        String REGISTER_TEMPLATE_CODE = "SMS_177185119";
        request.putQueryParameter("TemplateCode", REGISTER_TEMPLATE_CODE);
        request.putQueryParameter("TemplateParam", "{code: " + verifyCode + "}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            session.setAttribute("code", verifyCode);
            return ResponseUtils.response(ResponseUtils.SUCCESS, "发送验证码成功", null);
        } catch (ClientException e) {
            e.printStackTrace();
            throw new SystemErrorException();
        }
    }

    @ApiOperation(value = "验证短信验证码", notes = "验证短信验证码接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phoneNumber", value = "手机号", required = true, dataType = "string"),
            @ApiImplicitParam(name = "code", value = "验证码", required = true, dataType = "string")
    })
    @PostMapping("verify")
    public @ResponseBody
    String verifyRegisterSMS(@RequestBody JSONObject data) throws MyException {
        String code = (String) data.get("code");
        String phoneNumber = (String) data.get("phoneNumber");
        HttpSession session = ((ServletRequestAttributes)
                Objects.requireNonNull(RequestContextHolder.getRequestAttributes()))
                .getRequest()
                .getSession();
        String dbCode = (String) session.getAttribute("code");

        if (code.equals(dbCode)) {
            User user = this.userMapper.queryUserIdByTelephone(phoneNumber);
            session.setAttribute("userId", user.getUserId());
            return ResponseUtils.response(ResponseUtils.SUCCESS, "验证通过", null);
        } else {
            return ResponseUtils.response(ResponseUtils.FAILED, "验证码错误", null);
        }
    }

}
